<template>
    <div>
      <div class="input-section">
        <div class="right">
          <el-input
            v-model="searchActivityId"
            placeholder="请输入活动id"
            style="
              width: 400px;
              height: 40px;
              margin-bottom: 20px;
              margin-top: 20px;
              padding: 0px 10px;
            "
            :prefix-icon="Search"
            clearable
          />
          <el-input
            v-model="searchActivityName"
            placeholder="请输入活动名称"
            style="
              width: 400px;
              height: 40px;
              margin-bottom: 20px;
              margin-top: 20px;
              padding: 0px 10px;
            "
            :prefix-icon="Search"
            clearable
          />
          <el-button type="primary" @click="searchActivities">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <!-- 新增：Excel 按钮 -->
          <el-button @click="exportToExcel" type="success">导出 Excel</el-button>
        </div>
      </div>
      <el-table
        ref="tableRef"
        :data="tableData"
        style="width: 100%"
        row-key="id"
      >
      <el-table-column label="" width="50">
        <template #default="{ row }">
            <el-icon v-if="row.status === 0" color="green">
            <Sunrise />
            </el-icon>
            <el-icon v-else-if="row.status === 1" color="red">
            <Sunny />
            </el-icon>
            <el-icon v-else-if="row.status === 2" color="gray">
            <Sunset />
            </el-icon>
        </template>
        </el-table-column>
        <el-table-column prop="id" label="社团活动id" width="120" />
        <el-table-column prop="clubVO.clubName" label="所属社团" width="120" />
        <el-table-column prop="activityName" label="活动名" width="150" />
        <el-table-column prop="activityTitle" label="活动标题" width="150" />
         <el-table-column
          prop="startTime"
          label="活动开始时间"
          sortable
          width="150"
          :formatter="formatDate"
        />
        <el-table-column
          prop="endTime"
          label="活动结束时间"
          sortable
          width="150"
          :formatter="formatDate"
        />
        <el-table-column
          prop=" status"
          label="活动状态"
          width="120"
          :filters="statusFilters"
          :filter-method="filterType"
          filter-placement="bottom-end"
        >
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
            {{ scope.row.status }}
            </el-tag>
        </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{ row, $index }">
            <el-button size="small" @click="handleView(row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-section">
        <span class="record-count"> 共查询到 {{ total }} 条记录</span>
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          v-model:page-size="pageSize"
          v-model:current-page="currentPage"
          :page-sizes="[8, 16, 32, 64]"
          @current-change="handleCurrentChange"
        />
      </div>
      <!-- 查看活动详情的对话框 -->
      <el-dialog v-model="viewDialogVisible" title="活动详情" width="50%">
        <el-descriptions border :column="2">
          <el-descriptions-item label="活动ID">{{
            currentViewActivity.id
          }}</el-descriptions-item>
          <el-descriptions-item label="所属社团">{{
            currentViewActivity.clubName
          }}</el-descriptions-item>
          <el-descriptions-item label="活动名称">{{
            currentViewActivity.activityName
          }}</el-descriptions-item>
          <el-descriptions-item label="活动标题">{{
            currentViewActivity.activityTitle
          }}</el-descriptions-item>
          <el-descriptions-item label="活动内容" :span="2">
            <div style="white-space: pre-line">
              {{ currentViewActivity.activityContent }}
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="开始时间">{{
            formatDate(null, null, currentViewActivity.startTime)
          }}</el-descriptions-item>
          <el-descriptions-item label="结束时间">{{
            formatDate(null, null, currentViewActivity.endTime)
          }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(currentViewActivity.status)">
              {{ currentViewActivity.status }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </el-dialog>
    </div> 
  </template>

<script setup lang="ts">
import { ref ,computed} from "vue";
import { ElMessage } from "element-plus";
import { Search } from '@element-plus/icons-vue';
import { Sunrise, Sunny, Sunset } from '@element-plus/icons-vue';
import { useUserStore } from '../../../stores/user'
import { ActivityControllerService } from "../../../../generated/services/ActivityControllerService";
import { onMounted } from "vue";
import type { ActivityMembershipQueryRequest, ActivityVO } from "../../../../generated";

// const activities = ref<ShowedActivity[]>([]);
const store = useUserStore();  // 使用 Pinia 的用户存储
const nowUserId = store.id;
const tableData = ref<ActivityVO[]>([]);      // 表格数据
const pageSize = ref(8);
const currentPage = ref(1);
//计算总数
const total = computed(() => tableData.value?.length||0);     

// 显示用户的活动列表
// 使用 ActivityControllerService 获取用户活动列表
const loadActivities = async () => {
  try {
    const response = await ActivityControllerService.listActivityVoOfUserByPage({
      userId: nowUserId,               // 
      current: currentPage.value,     // 分页
      pageSize: pageSize.value,
    } as ActivityMembershipQueryRequest);

    
    if (response.code === 0 && response.data) {
      tableData.value = response.data.records as ActivityVO[];
      
    //   total.value = Number(response.data.current);

      // 打印每个活动的 status
      tableData.value.forEach((activity) => {
        console.log(`活动ID: ${activity.id}, 状态: ${activity.status}`);
      });
    } else {
      ElMessage.error("加载活动失败：" + response.message);
    }
  } catch (err) {
    console.error("请求出错：", err);
    ElMessage.error("网络请求异常！");
  }
};

onMounted(() => {
  loadActivities();  // 页面加载时自动查询
});



// 搜索相关
const searchActivityId = ref("");
const searchActivityName = ref("");

// 搜索活动
const searchActivities = async () => {
  try {
    const activityIdNumber = Number(searchActivityId.value);

    const isIdValid =
      searchActivityId.value &&
      !isNaN(activityIdNumber) &&
      activityIdNumber > 0;

    const hasActivityName = searchActivityName.value.trim().length > 0;

    if (!isIdValid && !hasActivityName) {
      ElMessage.warning("请输入有效的活动 ID 或活动名进行搜索");
      return;
    }

    // 请求所有数据（也可以做后端过滤优化）
    const response = await ActivityControllerService.listActivityVoOfUserByPage({
      userId: nowUserId,
      current: 1, // 重置页码
      pageSize: 1000, // 获取更多数据以便前端筛选
    });

    if (response.code === 0 && response.data) {
      let data = response.data.records as ActivityVO[];

      // 前端过滤：按活动 ID
      if (isIdValid) {
        data = data.filter((item) => item.id === activityIdNumber);
      }

      // 前端过滤：按活动名模糊匹配
      if (hasActivityName) {
        const lowerName = searchActivityName.value.toLowerCase();
        data = data.filter((item) =>
          item.activityName?.toLowerCase().includes(lowerName)
        );
      }

      tableData.value = data;
      currentPage.value = 1;
      ElMessage.success("搜索成功！");
    } else {
      ElMessage.warning("未查询到活动数据！");
    }
  } catch (error) {
    console.error("搜索出错：", error);
    ElMessage.error("搜索请求失败！");
  }
};

// 重置搜索
const resetSearch = () => {
  searchActivityId.value = "";
  searchActivityName.value = "";
  loadActivities();
  ElMessage.info("搜索已重置！");
};


const currentViewActivity = ref<any>({});
const viewDialogVisible = ref(false);

// 点击查看活动详情
const handleView = (row: any) => {
  currentViewActivity.value = row;
  // 从 row.clubVO 中提取社团信息
  if (row.clubVO) {
    currentViewActivity.value.clubName = row.clubVO.clubName; // 社团名称
    currentViewActivity.value.clubDescription = row.clubVO.description; // 社团描述
  }
    // 打开查看详情对话框
  viewDialogVisible.value = true;
};


// 分页变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  loadActivities();
};


// 格式化日期
const formatDate = (row: any, column: any, value: string) => {
  if (!value) return "";
  const date = new Date(value);
  return date.toLocaleString();
};

//处理状态文本和标签类型
// 状态过滤器
const statusFilters = [
  { text: "未开始", value: "确认举办" },
  { text: "进行中", value: "进行中" },
  { text: "已结束", value: "已结束" },
];


const getStatusTagType = (status: any) => {
  const s = status;
  if (s === "待审核" || s === "确定举办") return "success";
  if (s === "进行中") return "danger";
  if (s === "已结束" || s === "已取消") return "info";
  return "warning";
};


// 过滤方法

const filterType = (value: any, row: any, column: any) => {
  // 根据列的 `prop` 属性进行过滤
  if (column.property === "status") {
    return row.status === value;
  } else if (column.property === "isDelete") {
    return row.isDelete === value;
  }
  return false;
};


// 导出为 Excel
import * as XLSX from 'xlsx';
const fileInputRef = ref<HTMLInputElement | null>(null);

const exportToExcel = () => {
  if (!tableData.value.length) {
    ElMessage.warning('没有可导出的数据');
    return;
  }
  console.log("表格数据：", tableData.value);
  // 提取你想要导出的字段
  const exportData = tableData.value.map((item) => ({
    '社团活动ID': item.id,
    '所属社团': item.clubVO?.clubName || '未知社团',
    '活动名称': item.activityName || '暂无活动名',
    '活动标题': item.activityTitle || '暂无标题',
    '活动开始时间': item.startTime ? new Date(item.startTime).toLocaleString() : '未知',
    '活动结束时间': item.startTime ? new Date(item.startTime).toLocaleString() : '未知',
    '活动状态': item.status,
  }));

  const worksheet = XLSX.utils.json_to_sheet(exportData);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, '社团活动信息');

  // 下载 Excel 文件
  XLSX.writeFile(workbook, `社团活动列表_${new Date().toISOString().slice(0, 10)}.xlsx`);
};

</script>


<style scoped lang="scss">
.input-section {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;

  .right {
    display: flex;
    align-items: center;

    el-input {
      margin-right: 10px;
    }

    el-button {
      margin-left: 10px;
    }
  }
}

.el-table {
  margin-top: 20px;

  .el-table-column {
    text-align: center;
  }
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;

  .record-count {
    font-size: 14px;
    color: #666;
  }

  el-pagination {
    margin-left: auto;
  }
}

.el-dialog {
  .el-descriptions {
    margin-top: 10px;

    .el-descriptions-item {
      font-size: 14px;
      color: #333;

      div {
        white-space: pre-line;
      }
    }

    .el-tag {
      font-size: 12px;
    }
  }
}

.el-button {
  &.small {
    font-size: 12px;
    padding: 5px 10px;
  }
}
</style>